import qs from 'qs'
import axios, { HeadersDefaults } from 'axios'
import { ElMessage } from 'element-plus'
import { store } from '@/store/index'
import baseURL from '../variables/baseUrl'
import { storeStateType } from '@/common/types/store'

interface CommonHeaderProperties extends HeadersDefaults {
  'X-Requested-With': string;
  'Cache-Control': string;
  'X-Organ-Id': string;
  'X-City-Code': string;
  'Authorization': string;
}

const axiosInstance = axios.create({ 
  baseURL, 
  timeout: 1000 * 12 
})
axiosInstance.defaults.headers = {
  ...axiosInstance.defaults.headers,
  'X-Requested-With': 'XMLHttpRequest',
  'Cache-Control': 'no-cache'
} as CommonHeaderProperties
axiosInstance.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'

// 请求拦截器
axiosInstance.interceptors.request.use(
  (config) => {
      if (config.method === 'get') {
          config.paramsSerializer = params => qs.stringify(params, { arrayFormat: 'repeat' })
      }
      
      // 添加请求头认证
      const token = window.localStorage.getItem('token')
      if (token) {
        config.headers = {...config.headers, Authorization: token}
      }
      
      const _store = store as unknown as storeStateType
      config.headers = {
        ...config.headers,
        'X-Organ-Id': _store.state.base.branchData.orgLevelId,
        'X-City-Code': _store.state.base.branchData.cityCode
      }
      return config;
  },
  (err) => {
      return Promise.reject(err)
  }
)

// 响应拦截器
axiosInstance.interceptors.response.use(
  (res) => {
    if (res.status == 200) {
      return res.data
    }
  },
  (err) => {
    const { response } = err;
    if (response) {
      const msg = response?.data?.msg;
      switch (response.status) {
        case 400: // 400 请求返回错误信息
          ElMessage.error(msg || '错误代码：400')
          break
        case 401: { // 401 登陆过期
          ElMessage.error('登录过期，请重新登录')
          if (import.meta.env.PROD) {
            location.href = '/'
          }
          break
        }
        case 404: // 404请求不存在
          ElMessage.error('请求的资源不存在')
          break
        default:
          ElMessage.error(msg)
      }
    }
  }
)

export default axiosInstance